package net.vinote.sosa.web.servlet.view.json;

import java.io.OutputStream;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.AbstractView;

import com.alibaba.fastjson.JSONObject;

import net.vinote.sosa.core.json.JsonUtil;

/**
 * json响应
 *
 * @author Seer
 * @version MappingSosa2JsonView.java, v 0.1 2015年10月5日 下午9:45:01 Seer Exp.
 */
public class MappingSosa2JsonView extends AbstractView {

	public MappingSosa2JsonView() {
		setContentType("application/json");
	}

	@Override
	protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
		HttpServletResponse response) throws Exception {
		response.setContentType(getContentType());
		response.setCharacterEncoding("utf8");
		JSONObject json = new JSONObject();
		ModelAndView m = (ModelAndView) model.get("modelAndView");
		for (Entry<String, Object> entry : m.getModel().entrySet()) {
			if (StringUtils.startsWith(entry.getKey(), BindingResult.MODEL_KEY_PREFIX)) {
				continue;
			}
			JSONObject jo = JsonUtil.getJsonObject(entry.getValue());
			json.put(entry.getKey(), jo == null ? entry.getValue() : jo);
		}
		OutputStream out = response.getOutputStream();
		out.write(json.toString().getBytes());
		out.flush();
	}
 
}
